package com.saltlux.storm.study.bbs.impl.h2;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatabaseHelper {
	public static List<Map<String, String>> executeQuery(String queryString) {
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Connection conn = ConnectionManager.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(queryString);
			
			int columnCount = rs.getMetaData().getColumnCount();
			List<String> columnNames = new ArrayList<String>();
			for(int i=0; i<columnCount; i++) {
				columnNames.add(rs.getMetaData().getColumnName(i+1));
			}
			while(rs.next()) {
				Map<String, String> map = new HashMap<String, String>();
				for (String columnName : columnNames) {
					map.put(columnName.toUpperCase(), rs.getString(columnName));
				}
				result.add(map);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static boolean execute(String queryString) {
		boolean result = false;
		Statement stmt = null;
		try {
			Connection conn = ConnectionManager.getConnection();
			stmt = conn.createStatement();
			result = stmt.execute(queryString);
			ResultSet generatedKeys = stmt.getGeneratedKeys();
			while(generatedKeys.next()) {
				System.out.println(generatedKeys.getLong(1));
			}
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static Long executeInsertSingle(String queryString) {
		Long result = null;
		Statement stmt = null;
		try {
			Connection conn = ConnectionManager.getConnection();
			stmt = conn.createStatement();
			stmt.execute(queryString);
			ResultSet generatedKeys = stmt.getGeneratedKeys();
			if(generatedKeys.next()) {
				result = generatedKeys.getLong(1);
			}
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}
